package com.bj58.ecdata.mailreport.util;

import java.sql.Timestamp;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class DateUtil {

	/**
	 * 输入日期模式并把date日期对象转换为日期字符串
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String getStringDate(Date date, String pattern) {
		try {
			SimpleDateFormat f = new SimpleDateFormat(pattern);
			String strdate = f.format(date);
			return strdate;
		} catch (Exception pe) {
		}
		return null;
	}
	
	/**
	 * 输入日期，返回当月天数
	 * @param date
	 * @author zhaoxiang
	 * @return
	 */
	public static int getMonthDays(String date, String pattern) {
		try {
			Date d = strToDate(date,pattern);
		    Calendar now = Calendar.getInstance();  
		    now.setTime(d);
			return now.getActualMaximum(Calendar.DAY_OF_MONTH);
		} catch (Exception pe) {
			pe.printStackTrace();
		}
		return 30;
	}

	/**
	 * 输入日期，返回当月天数
	 * @param date
	 * @author zhaoxiang
	 * @return
	 */
	public static int getDayOfMonth(String date, String pattern) {
		try {
			Date d = strToDate(date,pattern);
		    Calendar now = Calendar.getInstance();  
		    now.setTime(d);
			return now.get(Calendar.DAY_OF_MONTH);
		} catch (Exception pe) {
			pe.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 将String时间转为Date格式，按照指定格式。
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date strToDate(String strDate, String patter) {
		SimpleDateFormat formatter = new SimpleDateFormat(patter);
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		return strtodate;
	}
	
	/**
	 * 输入日期，返回所在月份
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String getMonth(String date, String pattern,String monPattern) {
		try {
			if(StringUtils.isBlank(monPattern))
				monPattern = "yyyyMM";
			Date d = strToDate(date,pattern);
			return getStringDate(d,monPattern);
		} catch (Exception pe) {
			pe.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 输入日期，返回之前i月的月份
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String getMonthBefore(String date, String pattern, int i) {
		try {
			Date d = strToDate(date,pattern);
		    Calendar now = Calendar.getInstance();  
		    now.setTime(d);
		    now.add(Calendar.MONTH, -i);
			return getStringDate(now.getTime(),"yyyyMM");
		} catch (Exception pe) {
			pe.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 输入日期，返回之前i月第一天
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String firstDayMonthBefore(String date, String pattern, int i) {
		try {
			Date d = strToDate(date,pattern);
		    Calendar now = Calendar.getInstance();  
		    now.setTime(d);
		    now.add(Calendar.MONTH, -i);
		    now.set(Calendar.DAY_OF_MONTH,1);
			return getStringDate(now.getTime(),"yyyy-MM-dd");
		} catch (Exception pe) {
			pe.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 输入日期，返回之前i月最后一天
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String lastDayMonthBefore(String date, String pattern, int i) {
		try {
			Date d = strToDate(date,pattern);
		    Calendar now = Calendar.getInstance();  
		    now.setTime(d);
		    now.add(Calendar.MONTH, -i);
		    now.set(Calendar.DAY_OF_MONTH,now.getActualMaximum(Calendar.DAY_OF_MONTH));
			return getStringDate(now.getTime(),"yyyy-MM-dd");
		} catch (Exception pe) {
			pe.printStackTrace();
		}
		return null;
	}
	/**
	 * 获得到几个月后的时间
	 */  
	public static String getMonthAfter(String nowDate, int month) {  
	       Calendar now = Calendar.getInstance();  
	       Date d = strToDate(nowDate, "yyyy-MM-dd");
	       now.setTime(d);  
	       now.set(Calendar.MONTH, now.get(Calendar.MONTH) + month);  
	       return getStringDate(now.getTime(), "yyyy-MM-dd");
	 }  
	   
	/**
	 * 将String时间，按照指定格式，继续转为String
	 */
	public static String strToStr(String strDate, String patter) {
		Date  temp = DateUtil.strToDate(strDate, "yyyy-MM-dd");
		return 	DateUtil.getStringDate(temp, patter);
	}
	
	public static String strToStrBefore(String strDate,String patter,int day){
		Date tmpDate=strToDate(strDate,patter);
		tmpDate=getDateBefore2(tmpDate,day);
		return getStringDate(tmpDate,patter);
	}
	
	public static String strToStrAfter(String strDate,String patter,int day){
		Date tmpDate=strToDate(strDate,patter);
		tmpDate=getDateAfter(tmpDate,day);
		return getStringDate(tmpDate,patter);
	}
	
		/** @author zhaoxiang
	    * 获得到几天前的时间
	    * @param d 
	    * @param day 
	    * @return 
	    */ 
	 public static Date getDateBefore2(Date d, int day) {  
	       Calendar now = Calendar.getInstance();  
	       now.setTime(d);  
	       now.add(Calendar.DATE, -day);  
	       return now.getTime();  
	   }  
	
	/** 
	    *  
	    * 获得到几天前的时间
	    * @param d 
	    * @param day 
	    * @return 
	    */  
	   public static Date getDateBefore(Date d, int day) {  
	       Calendar now = Calendar.getInstance();  
	       now.setTime(d);  
	       now.set(Calendar.DATE, now.get(Calendar.DATE) - day);  
	       return now.getTime();  
	   }  
	   
		/** 
	    *  
	    * 获得到几天后的时间
	    * @param d 
	    * @param day 
	    * @return 
	    */  
	   public static Date getDateAfter(Date d, int day) {  
	       Calendar now = Calendar.getInstance();  
	       now.setTime(d);  
	       now.set(Calendar.DATE, now.get(Calendar.DATE) + day);  
	       return now.getTime();  
	   }  
	   
	   /**
		 * 将字符串解析为指定格式的日期对象
		 * @param strValue
		 * @return
		 */
		public static Date parseSimpleDateTime(String strValue,String patter) {
			try {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat(patter);
				Date date = simpleDateFormat.parse(strValue);
				return date;
			} catch (Exception e) {
				return null;
			}
		}
		
		/** 转换时间为字符串格式 自定义格式  */
		public static String getDateStringFromTimestamp(Timestamp tsp,String pattern) {
			Date date = new Date(tsp.getTime());
			SimpleDateFormat f = new SimpleDateFormat(pattern);
			return f.format(date);
		}
		
		/**获取月份（中文）列表
		 * @return
		 */
		public static List<String>  getMonthList(){
			List<String> monthList = new ArrayList<String	>();
			monthList.add("一月");monthList.add("二月");monthList.add("三月");
			monthList.add("四月");monthList.add("五月");monthList.add("六月");
			monthList.add("七月");monthList.add("八月");monthList.add("九月");
			monthList.add("十月");monthList.add("十一月");monthList.add("十二月");
			return monthList;
		}
		
		/**获取季度（中文）列表
		 * @return
		 */
		public static List<String>  getQuarterList(){
			List<String> quarterList = new ArrayList<String	>();
			quarterList.add("一季度");
			quarterList.add("二季度");
			quarterList.add("三季度");
			quarterList.add("四季度");
			return quarterList;
		}
		
		
		
		/**根据月份(中文)获取数字以便于拼写查询日期
		 * @param month
		 * @return
		 */
		public static String getMonthNum(String month){
			String result = "";
			if(month.equals("一月")){
				result = "1";
			}else if(month.equals("二月")){
				result = "2";
			}else if(month.equals("三月")){
				result = "3";
			}else if(month.equals("四月")){
				result = "4";
			}else if(month.equals("五月")){
				result = "5";
			}else if(month.equals("六月")){
				result = "6";
			}else if(month.equals("七月")){
				result = "7";
			}else if(month.equals("八月")){
				result = "8";
			}else if(month.equals("九月")){
				result = "9";
			}else if(month.equals("十月")){
				result = "10";
			}else if(month.equals("十一月")){
				result = "11";
			}else if(month.equals("十二月")){
				result = "12";
			}
			return result;
		}
		
		/**根据季度(中文)获取数字以便于拼写查询日期
		 * @param month
		 * @return
		 */
		public static String getQuarterNum(String month){
			String result = "";
			if(month.equals("一季度")){
				result = "1";
			}else if(month.equals("二季度")){
				result = "4";
			}else if(month.equals("三季度")){
				result = "7";
			}else if(month.equals("四季度")){
				result = "10";
			}
			return result;
		}
		
		
		/**获取当年年份
		 * @return
		 */
		@SuppressWarnings("static-access")
		public static String getCurYear(){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			String year =String.valueOf(calendar.get(calendar.YEAR));
			return year;
		}
		
		public static long getDateNum(Date afterdate, Date beforedate) {  
			long quot = 0;
			quot = afterdate.getTime() - beforedate.getTime();
			quot = quot / 1000 / 60 / 60 / 24;
			System.out.println(quot);
			return quot;
		}
		
		public static long getDistDates(Date startDate,Date endDate)    
	    {  
	        long totalDate = 0;  
	        Calendar calendar = Calendar.getInstance();  
	        calendar.setTime(startDate);  
	        long timestart = calendar.getTimeInMillis();  
	        calendar.setTime(endDate);  
	        long timeend = calendar.getTimeInMillis();  
	        totalDate = Math.abs((timeend - timestart))/(1000*60*60*24);  
	        return totalDate;  
	    }   
		
		   
			// 获得当前日期与本周日相差的天数
			private static int getMondayPlus() {
				Calendar cd = Calendar.getInstance();
				// 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
				int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 因为按中国礼拜一作为第一天所以这里减1
				if (dayOfWeek == 1) {
					return 0;
				} else {
					return 1 - dayOfWeek;
				}
			}
			
			// 获得本周一的日期
			public static String getMondayOFWeek() {
				int mondayPlus = getMondayPlus();
				GregorianCalendar currentDate = new GregorianCalendar();
				currentDate.add(GregorianCalendar.DATE, mondayPlus);
				Date monday = currentDate.getTime();

				SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
				String preMonday = formater.format(monday);
				return preMonday;
			}
			
			   
			/**
		    * 获得到X月后的时间
		    * @param d  当前日期
		    * @param month  月数
		    * @return 
		    */  
		   public static Date getDateAfterMonth(Date d, int month) {  
		       Calendar now = Calendar.getInstance();
		       now.setTime(d);  
		       
		       int year = now.get(Calendar.YEAR);
		       int setMonth = now.get(Calendar.MONTH) + month + 1;
		       int day =  now.get(Calendar.DAY_OF_MONTH);
		       
		       if(setMonth == 2 && day > 28){
		    	   if(year%400==0||(year %4==0&&year%100!=0)){  
		               day=29;  
		           }else{
		        	   day=28;  
		           }
		    	   now.set(Calendar.DAY_OF_MONTH,day);
		       }else if((setMonth==4||setMonth==6||setMonth==9||setMonth==11) && day==31){ 
		    	   day = 30;
		    	   now.set(Calendar.DAY_OF_MONTH,day);
		       }
		       now.set(Calendar.MONTH, now.get(Calendar.MONTH) + month);  
		       return now.getTime();  
		   }  
		   
		   /**
		    * 获得到X月前的时间
		    * @param d 当前日期
		    * @param month 月数
		    * @return 
		    */  
		   public static Date getDateBeforeMonth(Date d, int month) {  
			   Calendar now = Calendar.getInstance();
		       now.setTime(d);  
		       
		       int year = now.get(Calendar.YEAR);
		       int setMonth = now.get(Calendar.MONTH) - month + 1;
		       int day =  now.get(Calendar.DAY_OF_MONTH);
		       
		       if(setMonth == 2 && day > 28){
		    	   if(year%400==0||(year %4==0&&year%100!=0)){  
		               day=29;  
		           }else{
		        	   day=28;  
		           }
		    	   now.set(Calendar.DAY_OF_MONTH,day);
		       }else if((setMonth==4||setMonth==6||setMonth==9||setMonth==11) && day==31){ 
		    	   day = 30;
		    	   now.set(Calendar.DAY_OF_MONTH,day);
		       }
		       now.set(Calendar.MONTH, now.get(Calendar.MONTH) -  month);  
		       return now.getTime();  
		   }  
		   
		   
			/**根据起始日期获取横跨的所有月份OR年份
			 * @param startDate
			 * @param endDate
			 * @param patter  时间类型   yyyy:年   yyyyMM:月
			 * @return
			 */
			public static List<String> subDateByPatter(String startDate,String endDate,String patter){
				List<String> dateList = new ArrayList<String>();
				String end = DateUtil.getStringDate(DateUtil.strToDate(endDate, "yyyy-MM-dd"), patter);
				while(true){
					String start =DateUtil.getStringDate(DateUtil.strToDate(startDate, "yyyy-MM-dd"), patter);
					if(start.equals(end)){
						dateList.add(end);
						break;
					}else{
						dateList.add(start);
						int addMonth = 0;
						if("yyyy".equals(patter)){
							addMonth = 12;
						}else if("yyyyMM".equals(patter)){
							addMonth = 1;
						}
						startDate = DateUtil.getStringDate(DateUtil.getDateAfterMonth(DateUtil.strToDate(startDate, "yyyy-MM-dd"), addMonth), "yyyy-MM-dd");
					}
				}
				return dateList;
			}
			
			
			/**根据起始时间获取其所有日期段
			 * @param startDate
			 * @param endDate
			 * @return
			 */
			public static List<String> getDateList(String startDate,String endDate){
			 	
	        	List<String>  dateList = new ArrayList<String>();
				while(true){
					dateList.add(startDate);
					if(startDate.equals(endDate)){
						break;
					}
					startDate = DateUtil.getStringDate(DateUtil.getDateAfter(DateUtil.strToDate(startDate, "yyyy-MM-dd"), 1), "yyyy-MM-dd");
				}
				
				return dateList;
			}
			
			/**根据起始时间获取其所有日期段 , 返回格式为yyyyMMdd,类似天表名后缀
			 * @param startDate
			 * @param endDate
			 * @return
			 */
			public static List<String> getDayList(String startDate,String endDate){
				startDate = DateUtil.strToStr(startDate, "yyyyMMdd");
				endDate = DateUtil.strToStr(endDate, "yyyyMMdd");
				
	        	List<String>  dateList = new ArrayList<String>();
				while(true){
					dateList.add(startDate);
					if(startDate.equals(endDate)){
						break;
					}
					startDate = DateUtil.strToStrAfter(startDate, "yyyyMMdd" , 1);
				}
				
				return dateList;
			}
			
		    /**根据传入的日期获取其月份的第一天日期
		     * @param date
		     * @return
		     */
		    public static String getFirstDay(Date date) {
		        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
		        gcLast.setTime(date);
		        gcLast.set(Calendar.DAY_OF_MONTH, 1);
		        String day_first = df.format(gcLast.getTime());
		        StringBuffer str = new StringBuffer().append(day_first);
		        return str.toString();

		    }
		    
		    /**
		     * 获取当前日期是星期几 (1-7)
		     * 
		     * @param date
		     * @return 当前日期是星期几
		     */
		    public static int getWeekOfDate(Date date) {
		        Calendar cal = Calendar.getInstance();
		        cal.setTime(date);
		        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;// calendar.setFirstDayOfWeek(Calendar.MONDAY);
		        if(w == 0 ){
		        	w = 7;
		        }
		        return w;
		    }
		    
		    
		    /**跨月日期段拆分    将其拆分为  month;startDate;endDate
		     * @param beginDate   开始日期
		     * @param endDate    结束日期
		     * @return
		     */
		    public static List<String> subSearchDate(String beginDate, String endDate){
		    	List<String> monthList = DateUtil.subDateByPatter(beginDate, endDate, "yyyyMM");
				List<String> monthSearchList = new ArrayList<String>();
				
				String start_con = "";
				String end_con = "";
				for(String month : monthList){
					if(DateUtil.getStringDate(DateUtil.strToDate(beginDate, "yyyy-MM-dd"), "yyyyMM").equals(month)){
						start_con = beginDate;
					}else{
						start_con = month.substring(0,4)+"-"+month.substring(4)+"-01";
					}
					if(DateUtil.getStringDate(DateUtil.strToDate(endDate, "yyyy-MM-dd"), "yyyyMM").equals(month)){
						end_con = DateUtil.getStringDate(DateUtil.getDateAfter(DateUtil.strToDate(endDate, "yyyy-MM-dd"),1), "yyyy-MM-dd");
					}else{
						end_con = DateUtil.getStringDate(DateUtil.getDateAfterMonth(DateUtil.strToDate(month.substring(0,4)+"-"+month.substring(4)+"-01", "yyyy-MM-dd"), 1), "yyyy-MM-dd");
					}
					monthSearchList.add(month+";"+start_con+";"+end_con);
				}
				
		    	return monthSearchList;
		    }

		    public static void main(String args[]){
		    	System.out.println(getMonth("2015-04-05", "yyyy-MM-dd", "yyyy年M月"));
		    }
}
